package com.xing.controller;

import com.xing.http.BaseSearchService;
import com.xing.tools.MagnetSearchUtil;
import com.xing.tools.SingletonClient;
import com.xing.vo.Item;
import com.xing.vo.MatchConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/4/4 0004.
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {

    @Autowired
    private MagnetSearchUtil magnetSearchUtil;

    /**
     * 视频首页http://www.dmm.co.jp/digital/
     * 类型首页http://www.dmm.co.jp/digital/videoa/-/genre/
     * 厂商首页http://www.dmm.co.jp/digital/videoa/-/maker/
     * 女星首页http://www.dmm.co.jp/digital/videoa/-/actress/recommend/
     * 女星排行http://www.dmm.co.jp/digital/videoa/-/ranking/=/sort=ranking/type=actress/
     */
    @Autowired
    private BaseSearchService baseSearchService;

    @Autowired
    private List<MatchConfig> configList;

    @RequestMapping(value = "/digital/{sort}")
    public ModelAndView index(ModelAndView modelAndView,
                              @PathVariable(value = "sort") String sort,
                              @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("digital");
        List<Item> itemList = new ArrayList<>();
        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/device=tv/limit=30/sort=" + sort + "/page=" + page + "/";
        System.out.println(url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("ul#list > li");
//        String total = document.select("li.terminal > a").get(1).attr("href");
//        total = total.substring(total.indexOf("page=")+5,total.length()-1);
        for (Element element : elements) {
            Item item = new Item();
            String fan = element.select("p.tmb > a").first().attr("href");
            String title = element.select("span.txt").first().text();
            Elements acts = element.select("p.sublink > span > a");
            String act = "---";
            String actUrl = "";
            if (acts != null && acts.size() > 0) {
                act = acts.first().text();
                actUrl = acts.first().attr("href");
            }
            String id = wishFan(fan);
            if (!id.contains("-")) {
                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                Matcher m = p.matcher(id);
                if (m.find()) {
                    id = m.group(1) + "-" + m.group(2);
                }
            }
            if (!StringUtils.isEmpty(id)) {
                String img = element.select("span.img>img").first().attr("src");
                img = img.replace("pt.jpg", "pl.jpg");
                item.setId(id);
                item.setImg(img);
                item.setTitle(title);
                item.setActUrl(getAct(actUrl));
                item.setAct(act);
                item.setsId(getId(actUrl));
                itemList.add(item);
            }
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", 25);
        modelAndView.addObject("param", sort);
        modelAndView.addObject("itemList", itemList);

        return modelAndView;
    }

    @RequestMapping(value = "/index")
    public String index(){
        return "redirect:/digital/date";
    }

//    @RequestMapping(value = "/index")
//    public ModelAndView index(ModelAndView modelAndView) throws Exception {
//        modelAndView.setViewName("index");
//        List<Item> itemList = new ArrayList<>();
//        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/article="+article+"/limit=30/device=tv/id="+sid+"/sort=release_date/page="+page+"/";
//        System.out.println(url);
//        SingletonClient singletonClient = SingletonClient.getInstance();
//        String content = singletonClient.getContentWithProxy(url);
//        Document document = Jsoup.parse(content);
//        Elements elements = document.select("ul#list > li");
//        String total = document.select("li.terminal > a").get(1).attr("href");
//        total = total.substring(total.indexOf("page=")+5,total.length()-1);
//        for (Element element : elements) {
//            Item item = new Item();
//            String fan = element.select("p.tmb > a").first().attr("href");
//            String title = element.select("span.txt").first().text();
//            Elements acts = element.select("p.sublink > span > a");
//            String act = "---";
//            String actUrl = "";
//            if(acts != null && acts.size()>0) {
//                act = acts.first().text();
//                actUrl = acts.first().attr("href");
//            }
//            String id = wishFan(fan);
//            if(!id.contains("-")){
//                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
//                Matcher m = p.matcher(id);
//                if(m.find()){
//                    id = m.group(1) + "-" + m.group(2);
//                }
//            }
//            if (!StringUtils.isEmpty(id) && !id.startsWith("h")) {
//                String img = element.select("span.img>img").first().attr("src");
//                img = img.replace("pt.jpg", "pl.jpg");
//                item.setId(id);
//                item.setImg(img);
//                item.setTitle(title);
//                item.setActUrl(getAct(actUrl));
//                item.setAct(act);
//                item.setsId(getId(actUrl));
//                itemList.add(item);
//            }
//        }
//        modelAndView.addObject("page", page);
//        modelAndView.addObject("id",sid);
//        modelAndView.addObject("total",Integer.parseInt(total));
//        modelAndView.addObject("itemList", itemList);
//        modelAndView.addObject("article", article);
//        return modelAndView;
//    }

    @RequestMapping(value = "/digital/series/{id}")
    public ModelAndView series(ModelAndView modelAndView,
                                @PathVariable(value = "id") String sid,
                                @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("digital");

        List<Item> itemList = new ArrayList<>();
        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/article=series/id="+sid+"/limit=30/sort=date/page="+page+"/";
        System.out.println("actress-detail: " + url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("ul#list > li");

        String total = document.select("div.list-boxcaptside.list-boxpagenation > p").text();
        total = total.replaceAll("タイ.*","");
        int iTotal = Integer.parseInt(total)/30 + 1;
        for (Element element : elements) {
            Item item = new Item();
            String fan = element.select("p.tmb > a").first().attr("href");
            String title = element.select("span.txt").first().text();
            Elements acts = element.select("p.sublink > span > a");
            String act = "---";
            String actUrl = "";
            if (acts != null && acts.size() > 0) {
                act = acts.first().text();
                actUrl = acts.first().attr("href");
            }
            String id = wishFan(fan);
            if (!id.contains("-")) {
                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                Matcher m = p.matcher(id);
                if (m.find()) {
                    id = m.group(1) + "-" + m.group(2);
                }
            }
            if (!StringUtils.isEmpty(id)) {
//                System.out.println(title + " - " + id);
                String img = element.select("span.img>img").first().attr("src");
                img = img.replace("pt.jpg", "pl.jpg");
                item.setId(id);
                item.setImg(img);
                item.setActUrl(getAct(actUrl));
                item.setAct(act);
                item.setTitle(title);
                itemList.add(item);
            }
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", iTotal);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/digital/series")
    public ModelAndView series(ModelAndView modelAndView,
                            @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("series");

        String url = "http://www.dmm.co.jp/digital/videoa/-/ranking/=/term=monthly/type=series/page="+page+"/";
        System.out.println("series: " + url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("tr > td.bd-b");
        List<Item> itemList = new ArrayList<>();
        for(Element element:elements){
            Item item = new Item();
            String rank = element.select("span.rank").first().text();
            String img = element.select("a > img").first().attr("src");
            img = img.replace("pt.jpg","pl.jpg");
            Element data = element.select("div.data > p > a").first();
            if(data != null){
                String href = data.attr("href");
                href = href.substring(href.indexOf("id=")+3,href.lastIndexOf("/sort"));
                String name = data.text();
                item.setTitle(name);
                item.setsId(href);
            }
            item.setImg(img);
            item.setId(rank);
            itemList.add(item);
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", 5);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/digital/actress/{id}")
    public ModelAndView actress(ModelAndView modelAndView,
                                @PathVariable(value = "id") String sid,
                            @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("digital");

        List<Item> itemList = new ArrayList<>();
        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/article=actress/device=tv/id="+sid+"/limit=30/n1=DgRJTglEBQ4GpoD6,YyI,qs_/sort=date/page="+page+"/";
        System.out.println("actress-detail: " + url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("ul#list > li");

        String total = document.select("div.list-boxcaptside.list-boxpagenation > p").text();
        total = total.replaceAll("タイ.*","");
        int iTotal = Integer.parseInt(total)/30 + 1;
        for (Element element : elements) {
            Item item = new Item();
            String fan = element.select("p.tmb > a").first().attr("href");
            String title = element.select("span.txt").first().text();
            Elements acts = element.select("p.sublink > span > a");
            String act = "---";
            String actUrl = "";
            if (acts != null && acts.size() > 0) {
                act = acts.first().text();
                actUrl = acts.first().attr("href");
            }
            String id = wishFan(fan);
            if (!id.contains("-")) {
                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                Matcher m = p.matcher(id);
                if (m.find()) {
                    id = m.group(1) + "-" + m.group(2);
                }
            }
            if (!StringUtils.isEmpty(id)) {
//                System.out.println(title + " - " + id);
                String img = element.select("span.img>img").first().attr("src");
                img = img.replace("pt.jpg", "pl.jpg");
                item.setId(id);
                item.setImg(img);
                item.setActUrl(getAct(actUrl));
                item.setAct(act);
                item.setTitle(title);
                itemList.add(item);
            }
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", iTotal);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/digital/maker/{id}")
    public ModelAndView maker(ModelAndView modelAndView,
                              @PathVariable(value = "id") String sid,
                              @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("digital");
        List<Item> itemList = new ArrayList<>();
        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/article=maker/device=tv/id="+sid+"/limit=30/sort=date/page="+page+"/";

        System.out.println("maker: " + url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("ul#list > li");

        String total = document.select("div.list-boxcaptside.list-boxpagenation > p").text();
        total = total.replaceAll("タイ.*","");
        total = total.replace(",","");
        int iTotal = Integer.parseInt(total)/30 + 1;
        for (Element element : elements) {
            Item item = new Item();
            String fan = element.select("p.tmb > a").first().attr("href");
            String title = element.select("span.txt").first().text();
            Elements acts = element.select("p.sublink > span > a");
            String act = "---";
            String actUrl = "";
            if (acts != null && acts.size() > 0) {
                act = acts.first().text();
                actUrl = acts.first().attr("href");
            }
            String id = wishFan(fan);
            if (!id.contains("-")) {
                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                Matcher m = p.matcher(id);
                if (m.find()) {
                    id = m.group(1) + "-" + m.group(2);
                }
            }
            if (!StringUtils.isEmpty(id)) {
//                System.out.println(title + " - " + id);
                String img = element.select("span.img>img").first().attr("src");
                img = img.replace("pt.jpg", "pl.jpg");
                item.setId(id);
                item.setImg(img);
                item.setActUrl(getAct(actUrl));
                item.setAct(act);
                item.setTitle(title);
                itemList.add(item);
            }
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", iTotal);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/digital/maker")
    public ModelAndView maker(ModelAndView modelAndView) {
        modelAndView.setViewName("maker");

        String url = "http://www.dmm.co.jp/digital/videoa/-/maker/";
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("div.d-unit");
        List<Item> itemList = new ArrayList<>();
        for(Element element:elements){
            Item item = new Item();
            String img = element.select("span.d-tmb > span > img").first().attr("src");
            String title = element.select("span.d-ttllarge ").first().text();
            String id = element.select("div.d-boxpicdata.d-smalltmb > a").first().attr("href");
            id = id.substring(id.indexOf("id=")+3,id.lastIndexOf("/"));
            String desc = element.select("div.d-datacol > p").first().text();
            item.setImg(img);
            item.setId(id);
            item.setTitle(title);
            item.setDetailKey(desc);
            itemList.add(item);
        }
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/digital/actress")
    public ModelAndView act(ModelAndView modelAndView,
                            @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("actress");

        String url = "http://www.dmm.co.jp/digital/videoa/-/ranking/=/term=monthly/type=actress/page="+page+"/";
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("tr > td.bd-b");
        List<Item> itemList = new ArrayList<>();
        for(Element element:elements){
            Item item = new Item();
            String rank = element.select("span.rank").first().text();
            String img = element.select("a > img").first().attr("src");
            Element data = element.select("div.data > p > a").first();
            if(data != null){
                String href = data.attr("href");
                href = href.substring(href.indexOf("id=")+3,href.lastIndexOf("/"));
                String name = data.text();
                item.setTitle(name);
                item.setsId(href);
            }
            item.setImg(img);
            item.setId(rank);
            itemList.add(item);
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", 5);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/act/{name}")
    public ModelAndView act(ModelAndView modelAndView,
                            @PathVariable(value = "name") String name,
                            @RequestParam(defaultValue = "1", required = false) int page) {
        modelAndView.setViewName("digital");
        List<Item> itemList = new ArrayList<>();
        String url = "http://www.dmm.co.jp/digital/videoa/-/list/=/device=tv/limit=30/n1=" + name + "/n2=DgRJTglEBQ4GpoD6,YyI,qs_/sort=date/page="+page+"/";

        System.out.println("act: " + url);
        SingletonClient singletonClient = SingletonClient.getInstance();
        String content = singletonClient.getContentWithProxy(url);
        Document document = Jsoup.parse(content);
        Elements elements = document.select("ul#list > li");

        String total = document.select("div.list-boxcaptside.list-boxpagenation > p").text();
        total = total.replaceAll("タイ.*","");
        int iTotal = Integer.parseInt(total)/30 + 1;
        for (Element element : elements) {
            Item item = new Item();
            String fan = element.select("p.tmb > a").first().attr("href");
            String title = element.select("span.txt").first().text();
            String id = wishFan(fan);
            if (!id.contains("-")) {
                Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                Matcher m = p.matcher(id);
                if (m.find()) {
                    id = m.group(1) + "-" + m.group(2);
                }
            }
            if (!StringUtils.isEmpty(id)) {
//                System.out.println(title + " - " + id);
                String img = element.select("span.img>img").first().attr("src");
                img = img.replace("pt.jpg", "pl.jpg");
                item.setId(id);
                item.setImg(img);
                item.setTitle(title);
                itemList.add(item);
            }
        }
        modelAndView.addObject("page", page);
        modelAndView.addObject("total", iTotal);
        modelAndView.addObject("param", "");
        modelAndView.addObject("itemList", itemList);
        return modelAndView;
    }

    @RequestMapping(value = "/input2")
    public ModelAndView input2(ModelAndView modelAndView,String url,String sort) throws Exception{
        modelAndView.setViewName("input2");
        if(!StringUtils.isEmpty(url)){
            System.out.println("url is: " + url);

            if(!url.contains("sort") && !StringUtils.isEmpty(sort)){
                url = url + "sort=" + sort;
            }
            List<Item> itemList = new ArrayList<>();
            SingletonClient singletonClient = SingletonClient.getInstance();
            String content = singletonClient.getContentWithProxy(url);
            Document document = Jsoup.parse(content);
            Elements elements = document.select("ul#list > li");
            for (Element element : elements) {
                Item item = new Item();
                String fan = element.select("p.tmb > a").first().attr("href");
                String title = element.select("span.txt").first().text();
                Elements acts = element.select("p.sublink > span > a");
                String act = "---";
                String actUrl = "";
                if(acts != null && acts.size()>0) {
                    act = acts.first().text();
                    actUrl = acts.first().attr("href");
                }
                String id = wishFan(fan);
                if(!id.contains("-")){
                    Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                    Matcher m = p.matcher(id);
                    if(m.find()){
                        id = m.group(1) + "-" + m.group(2);
                    }
                }
                if (!StringUtils.isEmpty(id)) {
                    String img = element.select("span.img>img").first().attr("src");
                    if(img.contains("pt.jpg")){
                        img = img.replace("pt.jpg", "pl.jpg");
                    }else if(img.contains("ps.jpg")){
                        img = img.replace("ps.jpg", "pl.jpg");
                    }
                    item.setId(id);
                    item.setImg(img);
                    item.setTitle(title);
                    item.setActUrl(getAct(actUrl));
                    item.setAct(act);
                    item.setsId(getId(actUrl));
                    itemList.add(item);
                }
            }
            modelAndView.addObject("itemList", itemList);
        }
        return modelAndView;
    }

    @RequestMapping(value = "/input")
    public ModelAndView index2(ModelAndView modelAndView, String url, String sort) throws Exception {
        modelAndView.setViewName("input");
        if (!StringUtils.isEmpty(url)) {
            System.out.println("url is: " + url);

            if (!url.contains("sort") && !StringUtils.isEmpty(sort)) {
                url = url + "sort=" + sort;
            }
            List<Item> itemList = new ArrayList<>();
            SingletonClient singletonClient = SingletonClient.getInstance();
            String content = singletonClient.getContentWithProxy(url);
            Document document = Jsoup.parse(content);
            Elements elements = document.select("ul#list > li");
            for (Element element : elements) {
                Item item = new Item();
                String fan = element.select("p.tmb > a").first().attr("href");
                String title = element.select("span.txt").first().text();
                Elements acts = element.select("p.sublink > span > a");
                String act = "---";
                String actUrl = "";
                if (acts != null && acts.size() > 0) {
                    act = acts.first().text();
                    actUrl = acts.first().attr("href");
                }
                String id = wishFan(fan);
                if (!id.contains("-")) {
                    Pattern p = Pattern.compile("([a-z]*)(\\d*)");
                    Matcher m = p.matcher(id);
                    if (m.find()) {
                        id = m.group(1) + "-" + m.group(2);
                    }
                }
                if (!StringUtils.isEmpty(id)) {
                    String img = element.select("span.img>img").first().attr("src");
                    img = img.replace("pt.jpg", "pl.jpg");
                    item.setId(id);
                    item.setImg(img);
                    item.setTitle(title);
                    item.setActUrl(getAct(actUrl));
                    item.setAct(act);
                    item.setsId(getId(actUrl));
                    itemList.add(item);
                }
            }
            modelAndView.addObject("itemList", itemList);
        }
        return modelAndView;
    }

    private String getId(String url) {
        if (StringUtils.isEmpty(url)) {
            return "---";
        }
        url = url.substring(0, url.length() - 9);
        String temp = url.substring(url.indexOf("id=") + 3, url.lastIndexOf("/limit"));
        return temp;
    }

    private String getAct(String url) {
        if (StringUtils.isEmpty(url)) {
            return "---";
        }
        String temp = url.substring(url.indexOf("n1") + 3, url.lastIndexOf("/sort"));
        return temp;
    }

    @RequestMapping(value = "/json")
    @ResponseBody
    public String json(String id) throws Exception {
        System.out.println("json:" + id);
        String result = "";
        for(MatchConfig matchConfig:configList){
            result = baseSearchService.getMagnetById(id,matchConfig);
            if(!StringUtils.isEmpty(result)){
                break;
            }
        }
        System.out.println("result: " + result);
        return result;
    }


    private static String wishFan(String fan) {
        fan = fan.replace("h_", "");
        String f = fan.substring(fan.indexOf("cid") + 4, fan.length() - 1);
        if (f.contains("/")) {
            f = f.substring(0, f.indexOf("/"));
        }
        Pattern p = Pattern.compile("\\d*([a-z]*\\d*).*");
        Matcher m = p.matcher(f);
        if (m.find()) {
            return m.group(1).replaceFirst("00", "-");
        } else {
            System.out.println("番号识别失败: " + f);
        }
        return "";
    }
}
